# -*- coding: utf-8 -*-
import time

from pubsub import pub
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec

from zhi_dao.question import zhidao_exam
from zhi_dao import driver
from zhi_dao import driver_action
from zhi_dao import driver_wait
from zhi_dao.zhidao_const import event_question_done


# 测试题监控
def monitor():
    while True:
        try:
            topic_dialog = driver_wait.until(ec.presence_of_element_located((By.ID, "playTopic-dialog")))
        except Exception as te:
            topic_dialog = None
            # print(f"未获取到测试题弹窗，继续获取: {te}")
        if topic_dialog is None:
            continue
        answers = zhidao_exam.get_exam_answer(driver)
        right_contents = topic_dialog.find_elements(By.CSS_SELECTOR, ".right")
        print(right_contents)
        if len(right_contents) == 0:
            topic_items = topic_dialog.find_elements(By.CSS_SELECTOR, ".topic-item")
            for answer in answers:
                driver_action.click(topic_items[answer - 1]).perform()
        # 检查答案是否正确
        right_contents = topic_dialog.find_elements(By.CSS_SELECTOR, ".right")
        if len(right_contents) < 0:
            print("答案不正确")
            continue
        time.sleep(1)
        close_btn_list = topic_dialog.find_elements(By.CSS_SELECTOR, ".btn")
        if len(close_btn_list) > 0:
            driver_action.click(close_btn_list[0]).perform()
        time.sleep(2)
        pub.sendMessage(event_question_done)
        # video_player.play_video()
        # time.sleep(2)
